package it.disim.tlp.webreputation.dispatcher;

import it.disim.tlp.webreputation.aggregatorplugin.AggregatorPlugin;
import it.disim.tlp.webreputation.aggregatorplugin.ManifestedPlugin;
import it.disim.tlp.webreputation.business.AbstractDataAggregatorFactory;
import it.disim.tlp.webreputation.business.FactoryBuilder;
import it.disim.tlp.webreputation.business.SorgenteService;
import it.disim.tlp.webreputation.business.model.Sorgente;
import it.disim.tlp.webreputation.exceptions.AggregatorLogger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class AggregatorThread extends Thread {
	private ManifestedPlugin manPlugin;
	private AbstractDataAggregatorFactory factory;
	private List<Sorgente> sorgenti;
	private List<SorgenteTemp> sorgentiTemp;
	
	public AggregatorThread(ManifestedPlugin manPlugin){
		this.manPlugin = manPlugin;
		this.factory = FactoryBuilder.getInstance();
		SorgenteService sorgenteService = factory.getSorgenteService();
		this.sorgenti = sorgenteService.getSorgenti();
		this.sorgentiTemp = new ArrayList();
		
		for(Sorgente sorgente : sorgenti){
			SorgenteTemp tmp = new SorgenteTemp(sorgente);
			sorgentiTemp.add(tmp);
		}
		
	}
	
	private void sortByDate(){
		Collections.sort(sorgentiTemp);
	}
	
	public void run(){
		while(true){
			
			/* if no resource are loaded this thread is interrupted*/
			if(sorgentiTemp.size() == 0){
				interrupt(); 
			}
			
			/* sorting dated resources list by their dates*/
			this.sortByDate();
			
			/* getting the first resource with date more near to current date*/
			SorgenteTemp st = sorgentiTemp.get(0);
			
			/* various information*/
			Date now = new Date();
			String pluginName = manPlugin.getManifest().getName();
			AggregatorPlugin ap = manPlugin.getPlugin();
			int id = st.getSorgente().getId();
			
			/* calculating waiting time for that resource*/
			long time = st.getScheduled().getTime() - now.getTime();
			System.out.println("Executing plugin's thread "+pluginName+" on resource " + id + " and waiting time " + time);
			
			/* if time is major than 0 thread is slept until scheduled date is reached*/
			if (time > 0) {
				try {
					sleep(time);
				} catch (Exception e) {
					System.out.println("thread "+pluginName+" unlocked from sleep!"); /* handling that interrupt properly*/
				} 
			}
			
			/* getting posts from plugin*/
			System.out.println("taking posts from plugin..."+pluginName);
			try{
				System.out.println(ap.getPosts(st.getSorgente().getLink(),new Date()).get(0).getAuthor());
			} catch(Exception e){
				System.out.println("Errors during plugin "+pluginName+" execution... check log file inside logs directory.");
				AggregatorLogger.logging(pluginName, e);
			}
			
			/* calculating new scheduled date for that resource*/
			System.out.println("Update scheduled date on thread "+pluginName+" for resource "+id);
			st.calculateScheduledDate();
		}
	}
}